using SqlSugar;
using SqlsugarService.Application.DTOs.LMZWorkSchedule;
using SqlsugarService.Application.IService.LMZWorkSchedule;
using SqlsugarService.Application.Until;
using SqlsugarService.Domain;
using SqlsugarService.Domain.Craftsmanship;
using SqlsugarService.Domain.Plan;
using SqlsugarService.Domain.QualityInspection;
using SqlsugarService.Domain.Station;
using SqlsugarService.Domain.Team;
using SqlsugarService.Infrastructure.DbContext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SqlsugarService.Application.Service.LMZWorkSchedule
{
    /// <summary>
    /// LMZ质检系统服务实现类
    /// </summary>
    public class LMZWorkScheduleService : ILMZWorkScheduleService
    {
        #region 依赖注入

        private readonly SqlSugarDbContext _dbContext;

        public LMZWorkScheduleService(SqlSugarDbContext dbContext)
        {
            _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
        }

        #endregion

        #region LMZ质检系统基础列表

        /// <summary>
        /// 分页获取质检系统基础列表
        /// </summary>
        /// <param name="queryDto">查询参数</param>
        /// <returns>分页的质检列表</returns>
        public async Task<ApiResult<PageResult<List<LMZWorkScheduleListDto>>>> LMZGetWorkSchedulePagedAsync(LMZWorkScheduleQueryDto queryDto)
        {
            try
            {
                // 参数验证
                if (queryDto.PageIndex < 1)
                {
                    return ApiResult<PageResult<List<LMZWorkScheduleListDto>>>.Fail(
                        "页码必须大于0", ResultCode.ValidationError);
                }

                if (queryDto.PageSize < 1 || queryDto.PageSize > 1000)
                {
                    return ApiResult<PageResult<List<LMZWorkScheduleListDto>>>.Fail(
                        "每页大小必须在1-1000之间", ResultCode.ValidationError);
                }

                var query = _dbContext.Db.Queryable<WorkOrderTaskEntity>()
       .LeftJoin<ProductionOrder>((wot, po) => wot.Id == Guid.Empty)
       .LeftJoin<WorkReportInspectionEntity>((wot, po, wri) => wot.ProcessStepId == wri.ProcessStepId)
       .LeftJoin<Users>((wot, po, wri, u) => wri.InspectorId == u.Id)
       .Where((wot, po, wri, u) => wot.Status == "已报工")
       .Distinct();

                // 添加过滤条件
                if (!string.IsNullOrWhiteSpace(queryDto.OrderName))
                {
                    query = query.Where((wot, po, wri, u) => po.OrderName.Contains(queryDto.OrderName.Trim()));
                }

                if (!string.IsNullOrWhiteSpace(queryDto.Status))
                {
                    query = query.Where((wot, po, wri, u) => wot.Status == queryDto.Status.Trim());
                }

                // 获取总数
                var totalCount = await query.CountAsync();

                // 查询数据并直接映射到DTO，包含ProductionOrder的所有字段
                var data = await query
                    .OrderBy("wot.PlanStartTime desc")
                    .Skip((queryDto.PageIndex - 1) * queryDto.PageSize)
                    .Take(queryDto.PageSize)
                    .Select<LMZWorkScheduleListDto>("wri.Id, wot.SequenceNumber, wot.TaskNumber, wri.InspectionCode, wri.InspectionName, wri.InspectionType, wri.Status, wri.ProductId, wri.ProcessStepId, wot.ProcessName, wri.StationId, wri.TeamId, wri.ReporterId, wri.InspectorId, u.DisplayName as InspectorName, wri.ReportedQuantity, wri.ReportTime, wri.InspectionTime, wri.InspectionDepartment, wri.TestedQuantity, wri.QualifiedQuantity, wri.UnqualifiedQuantity, wri.OverallResult, wri.Remark, wot.PlanStartTime, po.OrderNumber, po.OrderName, po.ProductionPlanId, po.Specification, po.Unit, po.PlanQuantity as OrderPlanQuantity, po.ActualQuantity as OrderActualQuantity, po.PlanStartTime as OrderPlanStartTime, po.PlanEndTime as OrderPlanEndTime, po.ActualStartTime as OrderActualStartTime, po.ActualEndTime as OrderActualEndTime, po.Status as OrderStatus")
                    .ToListAsync();

                var pageResult = new PageResult<List<LMZWorkScheduleListDto>>
                {
                    Data = data,
                    TotalCount = totalCount,
                    TotalPage = (int)Math.Ceiling(totalCount * 1.0 / queryDto.PageSize)
                };

                return ApiResult<PageResult<List<LMZWorkScheduleListDto>>>.Success(pageResult, ResultCode.Success);
            }
            catch (Exception ex)
            {
                return ApiResult<PageResult<List<LMZWorkScheduleListDto>>>.Fail(
                    $"获取质检列表失败: {ex.Message}", ResultCode.Error);
            }
        }

        #endregion

        #region LMZ质检系统详细列表

        /// <summary>
        /// 分页获取质检系统详细列表
        /// </summary>
        /// <param name="queryDto">查询参数</param>
        /// <returns>分页的质检详细列表</returns>
        public async Task<ApiResult<PageResult<List<LMZWorkScheduleDetailDto>>>> LMZGetWorkScheduleDetailPagedAsync(LMZWorkScheduleQueryDto queryDto)
        {
            try
            {
                // 参数验证
                if (queryDto.PageIndex < 1)
                {
                    return ApiResult<PageResult<List<LMZWorkScheduleDetailDto>>>.Fail(
                        "页码必须大于0", ResultCode.ValidationError);
                }

                if (queryDto.PageSize < 1 || queryDto.PageSize > 1000)
                {
                    return ApiResult<PageResult<List<LMZWorkScheduleDetailDto>>>.Fail(
                        "每页大小必须在1-1000之间", ResultCode.ValidationError);
                }

                // 构建复杂查询 - 关联多个表
                var query = _dbContext.Db.Queryable<WorkOrderTaskEntity>()
                    .LeftJoin<ProductionOrder>((wot, po) => wot.ProductionOrderId == po.Id)
                    .LeftJoin<WorkReportInspectionEntity>((wot, po, wri) => wot.ProcessStepId == wri.ProcessStepId)
                    .LeftJoin<StationEntity>((wot, po, wri, s) => wot.StationName == s.StationName)
                    .LeftJoin<TeamEntity>((wot, po, wri, s, t) => wri.TeamId == t.Id)
                    .LeftJoin<Users>((wot, po, wri, s, t, u) => wri.InspectorId == u.Id);

                // 添加过滤条件
                if (!string.IsNullOrWhiteSpace(queryDto.OrderName))
                {
                    query = query.Where((wot, po, wri, s, t, u) => po.OrderName.Contains(queryDto.OrderName.Trim()));
                }

                if (!string.IsNullOrWhiteSpace(queryDto.Status))
                {
                    query = query.Where((wot, po, wri, s, t, u) => wot.Status == queryDto.Status.Trim());
                }

                // 获取总数
                var totalCount = await query.CountAsync();

                // 查询数据并直接映射到DTO，包含ProductionOrder的所有字段
                var data = await query
                    .OrderBy("wot.PlanStartTime desc")
                    .Skip((queryDto.PageIndex - 1) * queryDto.PageSize)
                    .Take(queryDto.PageSize)
                    .Select<LMZWorkScheduleDetailDto>("wot.SequenceNumber, wot.TaskNumber, wri.InspectionCode, po.OrderName, wot.TaskName, wot.StationName, wot.ProcessName, po.ProductName, po.ProductNumber, t.TeamName, '' as ResponsiblePerson, u.DisplayName as InspectorName, wot.PlanQuantity, wot.Status, po.OrderNumber, po.ProductionPlanId, po.Specification, po.Unit, po.PlanQuantity as OrderPlanQuantity, po.ActualQuantity as OrderActualQuantity, po.PlanStartTime as OrderPlanStartTime, po.PlanEndTime as OrderPlanEndTime, po.ActualStartTime as OrderActualStartTime, po.ActualEndTime as OrderActualEndTime, po.Status as OrderStatus")
                    .ToListAsync();

                var pageResult = new PageResult<List<LMZWorkScheduleDetailDto>>
                {
                    Data = data,
                    TotalCount = totalCount,
                    TotalPage = (int)Math.Ceiling(totalCount * 1.0 / queryDto.PageSize)
                };

                return ApiResult<PageResult<List<LMZWorkScheduleDetailDto>>>.Success(pageResult, ResultCode.Success);
            }
            catch (Exception ex)
            {
                return ApiResult<PageResult<List<LMZWorkScheduleDetailDto>>>.Fail(
                    $"获取质检详细列表失败: {ex.Message}", ResultCode.Error);
            }
        }

        #endregion

        #region LMZ质检详情

        /// <summary>
        /// 根据ID获取质检详情
        /// </summary>
        /// <param name="taskId">任务ID</param>
        /// <returns>质检详情</returns>
        public async Task<ApiResult<LMZWorkScheduleDetailDto>> LMZGetWorkScheduleByIdAsync(Guid taskId)
        {
            try
            {
                // 查询单个任务的详细信息，包含ProductionOrder的所有字段
                var queryResult = await _dbContext.Db.Queryable<WorkOrderTaskEntity>()
                    .LeftJoin<ProductionOrder>((wot, po) => wot.ProductionOrderId == po.Id)
                    .LeftJoin<WorkReportInspectionEntity>((wot, po, wri) => wot.ProcessStepId == wri.ProcessStepId)
                    .LeftJoin<StationEntity>((wot, po, wri, s) => wot.StationName == s.StationName)
                    .LeftJoin<TeamEntity>((wot, po, wri, s, t) => wri.TeamId == t.Id)
                    .LeftJoin<Users>((wot, po, wri, s, t, u) => wri.InspectorId == u.Id)
                    .Where((wot, po, wri, s, t, u) => wot.Id == taskId)
                    .Select((wot, po, wri, s, t, u) => new
                    {
                        SequenceNumber = wot.SequenceNumber,
                        TaskNumber = wot.TaskNumber,
                        InspectionCode = wri.InspectionCode,
                        OrderName = po.OrderName,
                        TaskName = wot.TaskName,
                        StationName = wot.StationName,
                        ProcessName = wot.ProcessName,
                        ProductName = po.ProductName,
                        ProductNumber = po.ProductNumber,
                        TeamName = t.TeamName,
                        ResponsiblePerson = string.Empty,
                        InspectorName = u.DisplayName ?? u.Username,
                        PlanQuantity = wot.PlanQuantity,
                        Status = wot.Status,
                        // ProductionOrder 字段
                        OrderNumber = po.OrderNumber,
                        ProductionPlanId = po.ProductionPlanId,
                        Specification = po.Specification,
                        Unit = po.Unit,
                        OrderPlanQuantity = po.PlanQuantity,
                        OrderActualQuantity = po.ActualQuantity,
                        OrderPlanStartTime = po.PlanStartTime,
                        OrderPlanEndTime = po.PlanEndTime,
                        OrderActualStartTime = po.ActualStartTime,
                        OrderActualEndTime = po.ActualEndTime,
                        OrderStatus = po.Status
                    })
                    .FirstAsync();

                if (queryResult == null)
                {
                    return ApiResult<LMZWorkScheduleDetailDto>.Fail("质检任务不存在", ResultCode.NotFound);
                }

                // 转换为DTO，包含ProductionOrder的所有字段
                var result = new LMZWorkScheduleDetailDto
                {
                    SequenceNumber = queryResult.SequenceNumber,
                    TaskNumber = queryResult.TaskNumber ?? string.Empty,
                    InspectionCode = queryResult.InspectionCode ?? string.Empty,
                    OrderName = queryResult.OrderName ?? string.Empty,
                    TaskName = queryResult.TaskName ?? string.Empty,
                    StationName = queryResult.StationName ?? string.Empty,
                    ProcessName = queryResult.ProcessName ?? string.Empty,
                    ProductName = queryResult.ProductName ?? string.Empty,
                    ProductNumber = queryResult.ProductNumber ?? string.Empty,
                    TeamName = queryResult.TeamName ?? string.Empty,
                    ResponsiblePerson = queryResult.ResponsiblePerson ?? string.Empty,
                    InspectorName = queryResult.InspectorName ?? string.Empty,
                    PlanQuantity = queryResult.PlanQuantity,
                    Status = queryResult.Status ?? string.Empty,
                    // ProductionOrder 字段
                    OrderNumber = queryResult.OrderNumber ?? string.Empty,
                    ProductionPlanId = queryResult.ProductionPlanId,
                    Specification = queryResult.Specification ?? string.Empty,
                    Unit = queryResult.Unit ?? string.Empty,
                    OrderPlanQuantity = queryResult.OrderPlanQuantity,
                    OrderActualQuantity = queryResult.OrderActualQuantity,
                    OrderPlanStartTime = queryResult.OrderPlanStartTime,
                    OrderPlanEndTime = queryResult.OrderPlanEndTime,
                    OrderActualStartTime = queryResult.OrderActualStartTime,
                    OrderActualEndTime = queryResult.OrderActualEndTime,
                    OrderStatus = queryResult.OrderStatus ?? string.Empty
                };



                return ApiResult<LMZWorkScheduleDetailDto>.Success(result, ResultCode.Success);
            }
            catch (Exception ex)
            {
                return ApiResult<LMZWorkScheduleDetailDto>.Fail(
                    $"获取质检详情失败: {ex.Message}", ResultCode.Error);
            }
        }

        #endregion

        #region LMZ质检记录列表

        /// <summary>
        /// 分页获取质检记录列表（只显示已质检状态）
        /// </summary>
        /// <param name="queryDto">查询参数</param>
        /// <returns>分页的质检记录列表</returns>
        public async Task<ApiResult<PageResult<List<LMZWorkScheduleListDto>>>> LMZGetInspectionRecordsPagedAsync(LMZWorkScheduleQueryDto queryDto)
        {
            try
            {
                // 参数验证
                if (queryDto.PageIndex < 1)
                {
                    return ApiResult<PageResult<List<LMZWorkScheduleListDto>>>.Fail(
                        "页码必须大于0", ResultCode.ValidationError);
                }

                if (queryDto.PageSize < 1 || queryDto.PageSize > 1000)
                {
                    return ApiResult<PageResult<List<LMZWorkScheduleListDto>>>.Fail(
                        "每页大小必须在1-1000之间", ResultCode.ValidationError);
                }

                // 构建查询 - 关联工单任务表和质检表，只查询已质检状态
                var query = _dbContext.Db.Queryable<WorkOrderTaskEntity>()
                    .LeftJoin<ProductionOrder>((wot, po) => wot.ProductionOrderId == po.Id)
                    .LeftJoin<WorkReportInspectionEntity>((wot, po, wri) => wot.ProcessStepId == wri.ProcessStepId)
                    .LeftJoin<Users>((wot, po, wri, u) => wri.InspectorId == u.Id)
                    .LeftJoin<QualityInspectionPlanWorkReportEntity>((wot, po, wri, u, qipwre) => wri.Id == qipwre.WorkReportInspectionId)
                    .Where((wot, po, wri, u, qipwre) => wri.Status == "已质检"); // 只显示已质检状态

                // 添加过滤条件
                if (!string.IsNullOrWhiteSpace(queryDto.OrderName))
                {
                    query = query.Where((wot, po, wri, u, qipwre) => po.OrderName.Contains(queryDto.OrderName.Trim()));
                }

                // 获取总数
                var totalCount = await query.CountAsync();

                // 查询数据并直接映射到DTO，包含ProductionOrder和QualityInspectionPlanWorkReportEntity的所有字段
                var data = await query
                    .OrderBy("wot.PlanStartTime desc")
                    .Skip((queryDto.PageIndex - 1) * queryDto.PageSize)
                    .Take(queryDto.PageSize)
                    .Select<LMZWorkScheduleListDto>("wri.Id, wot.SequenceNumber, wot.TaskNumber, wri.InspectionCode, wri.InspectionName, wri.InspectionType, wri.Status, wri.ProductId, wri.ProcessStepId, wot.ProcessName, wri.StationId, wri.TeamId, wri.ReporterId, wri.InspectorId, u.DisplayName as InspectorName, wri.ReportedQuantity, wri.ReportTime, wri.InspectionTime, wri.InspectionDepartment, wri.TestedQuantity, wri.QualifiedQuantity, wri.UnqualifiedQuantity, wri.OverallResult, wri.Remark, wot.PlanStartTime, po.OrderNumber, po.OrderName, po.ProductionPlanId, po.Specification, po.Unit, po.PlanQuantity as OrderPlanQuantity, po.ActualQuantity as OrderActualQuantity, po.PlanStartTime as OrderPlanStartTime, po.PlanEndTime as OrderPlanEndTime, po.ActualStartTime as OrderActualStartTime, po.ActualEndTime as OrderActualEndTime, po.Status as OrderStatus, qipwre.Id as QualityInspectionPlanWorkReportId, qipwre.QualityInspectionPlanId, qipwre.WorkReportInspectionId, qipwre.IsCurrentVersion, qipwre.EffectiveTime, qipwre.ExpiryTime, qipwre.Remark as QualityInspectionRemark")
                    .ToListAsync();

                var pageResult = new PageResult<List<LMZWorkScheduleListDto>>
                {
                    Data = data,
                    TotalCount = totalCount,
                    TotalPage = (int)Math.Ceiling(totalCount * 1.0 / queryDto.PageSize)
                };

                return ApiResult<PageResult<List<LMZWorkScheduleListDto>>>.Success(pageResult, ResultCode.Success);
            }
            catch (Exception ex)
            {
                return ApiResult<PageResult<List<LMZWorkScheduleListDto>>>.Fail(
                    $"获取质检记录列表失败: {ex.Message}", ResultCode.Error);
            }
        }

        #endregion

        #region 质检方案列表

        /// <summary>
        /// 获取质检方案列表
        /// </summary>
        /// <returns>质检方案列表</returns>
        public async Task<ApiResult<List<QualityInspectionDto>>> LMZGetQualityInspectionPlansAsync()
        {
            try
            {
                
                // 查询质检方案数据，关联版本信息
                var data = await _dbContext.Db.Queryable<QualityInspectionPlanEntity>()
                    .LeftJoin<QualityInspectionPlanWorkReportEntity>((qip, qipwr) => qip.Id == qipwr.QualityInspectionPlanId && qipwr.IsCurrentVersion == true)
                    .Select((qip, qipwr) => new QualityInspectionDto
                    {
                        Id = qip.Id,
                        PlanName = qip.PlanName ?? string.Empty,
                        PlanCode = qip.PlanCode ?? string.Empty,
                        DetectionCategory = qip.DetectionCategory ?? string.Empty,
                        DetectionTypes = qip.DetectionTypes ?? string.Empty,
                        Status = qip.Status ?? string.Empty,
                        Remark = qip.Remark ?? string.Empty,
                        Version = qipwr.Version,
                        VersionDescription = qipwr.VersionDescription ?? string.Empty,
                        IsCurrentVersion = qipwr.IsCurrentVersion,
                        EffectiveTime = qipwr.EffectiveTime,
                        ExpiryTime = qipwr.ExpiryTime
                    })
                    .ToListAsync();
                return ApiResult<List<QualityInspectionDto>>.Success(data, ResultCode.Success);
            }
            catch (Exception ex)
            {
                // 返回5条测试数据
                var testData = new List<QualityInspectionDto>
                {
                    new QualityInspectionDto
                    {
                        PlanName = "产品首检方案",
                        PlanCode = "QC001",
                        DetectionCategory = "产品",
                        DetectionTypes = "首检,自检",
                        Status = "启用",
                        Remark = "产品生产首检质量控制方案",
                        Version = 1,
                        VersionDescription = "初始版本",
                        IsCurrentVersion = true,
                        EffectiveTime = DateTime.Now.AddDays(-30),
                        ExpiryTime = null
                    },
                    new QualityInspectionDto
                    {
                        PlanName = "物料入库检验方案",
                        PlanCode = "QC002",
                        DetectionCategory = "物料",
                        DetectionTypes = "入库检验,抽检",
                        Status = "启用",
                        Remark = "原材料入库质量检验标准方案",
                        Version = 2,
                        VersionDescription = "优化检验流程",
                        IsCurrentVersion = true,
                        EffectiveTime = DateTime.Now.AddDays(-15),
                        ExpiryTime = null
                    },
                    new QualityInspectionDto
                    {
                        PlanName = "成品出厂检验方案",
                        PlanCode = "QC003",
                        DetectionCategory = "产品",
                        DetectionTypes = "终检,出厂检验",
                        Status = "启用",
                        Remark = "成品出厂前最终质量检验方案",
                        Version = 1,
                        VersionDescription = "标准检验方案",
                        IsCurrentVersion = true,
                        EffectiveTime = DateTime.Now.AddDays(-20),
                        ExpiryTime = null
                    },
                    new QualityInspectionDto
                    {
                        PlanName = "工序中间检验方案",
                        PlanCode = "QC004",
                        DetectionCategory = "产品",
                        DetectionTypes = "中检,工序检验",
                        Status = "禁用",
                        Remark = "生产工序中间环节质量检验方案",
                        Version = 3,
                        VersionDescription = "暂停使用，待优化",
                        IsCurrentVersion = false,
                        EffectiveTime = DateTime.Now.AddDays(-60),
                        ExpiryTime = DateTime.Now.AddDays(-10)
                    },
                    new QualityInspectionDto
                    {
                        PlanName = "设备维护检验方案",
                        PlanCode = "QC005",
                        DetectionCategory = "设备",
                        DetectionTypes = "设备检验,维护检查",
                        Status = "启用",
                        Remark = "生产设备定期维护质量检验方案",
                        Version = 1,
                        VersionDescription = "设备检验标准方案",
                        IsCurrentVersion = true,
                        EffectiveTime = DateTime.Now.AddDays(-5),
                        ExpiryTime = null
                    }
                };

                return ApiResult<List<QualityInspectionDto>>.Success(testData, ResultCode.Success);
            }
        }

        #endregion
    }
}